package com.wwp.info;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.Toast;

public class WebFullScreenActivity extends Activity {
	 WebView webView;
	 
	 public final static int FILECHOOSER_RESULTCODE = 1;  
	 public final static int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 2;  
	 public ValueCallback<Uri> mUploadMessage;  
	 public ValueCallback<Uri[]> mUploadMessageForAndroid5; 
	 
     @SuppressLint({ "NewApi", "SetJavaScriptEnabled" })
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_item);
       
         webView = (WebView) findViewById(R.id.webView);
         WebSettings webSettings = webView.getSettings();
        
        webSettings.setJavaScriptEnabled(true);
        String url = getIntent().getStringExtra("url");
        webView.addJavascriptInterface(new JsInterface(this), "AndroidWebView");
        if(!NetHelper.IsHaveInternet(this)) {
      	  webSettings.setCacheMode(webSettings.LOAD_CACHE_ELSE_NETWORK);
      }else {
      	  webSettings.setCacheMode(webSettings.LOAD_NO_CACHE);
      }

        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLoadsImagesAutomatically(true);
        
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();

        webSettings.setAppCachePath(appCachePath);

        webSettings.setAllowFileAccess(true);

        webSettings.setAppCacheEnabled(true);
        
      //启用数据库  
        webSettings.setDatabaseEnabled(true);    
        String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); 
        //启用地理定位  
        webSettings.setGeolocationEnabled(true);  
        //设置定位的数据库路径  
        webSettings.setGeolocationDatabasePath(dir);   

        //最重要的方法，一定要设置，这就是出不来的主要原因
        webSettings.setDomStorageEnabled(true);
       
        webView.setWebChromeClient(new WebChromeClient() {  
            @SuppressWarnings("unused")
			public boolean shouldOverrideUrlLoading(WebView view, String url) {   
                view.loadUrl(url);  
                return true;  
            }  
            @SuppressWarnings("unused")
			public boolean onJsAlert(WebView view,String url,String message,JsResult result){
            	return onJsAlert(view,url,message,result);
            	};
            	
            	 //配置权限（同样在WebChromeClient中实现）  
            	@SuppressWarnings("unused")
				public void onGeolocationPermissionsShowPrompt(String origin,   
                        GeolocationPermissions.Callback callback) {  
            		  super.onGeolocationPermissionsShowPrompt(origin, callback); 
                     callback.invoke(origin, true, false);  
                     } 
            
            	

		 public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> uploadMsg, WebChromeClient.FileChooserParams fileChooserParams) {
		      openFileChooserImplForAndroid5(uploadMsg);
		       return true;
		 }
        });  
       
       
         webView.loadUrl(url);
    }
     
	private void openFileChooserImpl(ValueCallback<Uri> uploadMsg) {
		mUploadMessage = uploadMsg;
		Intent i = new Intent(Intent.ACTION_GET_CONTENT);
		i.addCategory(Intent.CATEGORY_OPENABLE);
		i.setType("image/*");
		startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
	}

	private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg) {
		mUploadMessageForAndroid5 = uploadMsg;
		Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
		contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
		contentSelectionIntent.setType("image/*");
		Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
		chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
		chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
		startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == FILECHOOSER_RESULTCODE) {
			if (null == mUploadMessage)
				return;
			Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
			mUploadMessage.onReceiveValue(result);
			mUploadMessage = null;
		} else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
			if (null == mUploadMessageForAndroid5)
				return;
			Uri result = (intent == null || resultCode != RESULT_OK) ? null : intent.getData();
			if (result != null) {
				mUploadMessageForAndroid5.onReceiveValue(new Uri[] { result });
			} else {
				mUploadMessageForAndroid5.onReceiveValue(new Uri[] {});
			}
			mUploadMessageForAndroid5 = null;
		}
	}

    private class JsInterface {
        private Context mContext;

        public JsInterface(Context context) {
            this.mContext = context;
        }

        @JavascriptInterface
        public void showInfoFromJs(String name) {
            Toast.makeText(mContext, name, Toast.LENGTH_SHORT).show();
            finish();
        }
    }

//    public void sendInfoToJs(View view) {
//        String msg = ((EditText) findViewById(R.id.input_et)).getText().toString();
//        webView.loadUrl("javascript:showInfoFromJava('" + msg + "')");
//    }
//    
    
//    @Override  
//    protected void onActivityResult(int requestCode, int resultCode,  
//            Intent intent) {  
//        if (requestCode == FILECHOOSER_RESULTCODE) {  
//            if (null == mUploadMessage)  
//                return;  
//            Uri result = intent == null || resultCode != RESULT_OK ? null  
//                    : intent.getData();  
//            mUploadMessage.onReceiveValue(result);  
//            mUploadMessage = null;  
//      
//        } else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {  
//            if (null == mUploadMessageForAndroid5)  
//                return;  
//            Uri result = (intent == null || resultCode != RESULT_OK) ? null  
//                    : intent.getData();  
//            if (result != null) {  
//                mUploadMessageForAndroid5.onReceiveValue(new Uri[] { result });  
//            } else {  
//                mUploadMessageForAndroid5.onReceiveValue(new Uri[] {});  
//            }  
//            mUploadMessageForAndroid5 = null;  
//        }  
//    }   
}
